package com.centit.bod.kaixin001.ui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;

import javax.swing.JTextArea;
import javax.swing.text.Document;

public class ConsoleTextArea extends JTextArea {
	
	private static final long serialVersionUID = 5077628054092152668L;
	
	public ConsoleTextArea(boolean isOut) {
		LoopedStreams ls;
		try {
			ls = new LoopedStreams();
			PrintStream ps = new PrintStream(ls.getOutputStream());
			if(isOut){
				System.setOut(ps);
			}else{
				System.setErr(ps);
			}
			startConsoleReaderThread(ls.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void startConsoleReaderThread(InputStream inStream) {
		final BufferedReader br = new BufferedReader(new InputStreamReader(
				inStream));
		new Thread(new Runnable() {
			public void run() {
				StringBuffer sb = new StringBuffer();
				try {
					String s;
					Document doc = getDocument();
					while ((s = br.readLine()) != null) {
						boolean caretAtEnd = false;
						caretAtEnd = getCaretPosition() == doc.getLength() ? true
								: false;
						sb.setLength(0);
						append(sb.append(s).append("\n").toString());
						if (caretAtEnd)
							setCaretPosition(doc.getLength());
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	} 


} 
